package com.grj.service.article.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.UUID;


/**
 * @author 14505
 */
@Component
public class RabbitMQConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback{
    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            String id = UUID.randomUUID().toString();
            correlationData.setId(id);
            System.out.println("已投递到交换机: "+id);
            return;
        }
        System.out.println("投递到交换机失败, 放入缓存, 定时重发,"+cause);
    }




    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("没有投递到队列");
    }



    @Bean("exchange")
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange("exchange").durable(true).build();
    }


    @Bean("queue")
    public Queue queue(){
        return QueueBuilder
                .durable("queue")
                .ttl(1000*60)
                .build();
    }

    @Bean("binding")
    public Binding binding(@Qualifier("queue") Queue queue, @Qualifier("exchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("update").noargs();
    }

}
